//
//  BaseCell.swift
//  SinaWb
//
//  Created by Jiang on 5/30/16.
//  Copyright © 2016 Jiang. All rights reserved.
//
import UIKit
import SDWebImage

//MARK: -
class BaseCell: UITableViewCell{
    
    var pic_urlArray :[String]?
    
    //MARK: 获取Cell的高度
    func getTheHight(statu:JkmCellStatus)->(CGFloat){
        status = statu
        layoutIfNeeded()
        return toolview.frame.maxY
    }
    
    ///设置配图的数量
    func setCollectinViewImageCount()->(Int?){
        return nil
    }
    
    /// 一张图时的URL
    func setBackViewimageKey()->(String?){
        return nil
    }
    
    /// 设置配图的url数组
    func setPic_urlArray()->( [String]? ){
        return nil
    }
    
    //MARK: 设置所有子视图的内容
    var status : JkmCellStatus?{
        
        didSet{
            statusDidSetted()
        }
    }
    
    func statusDidSetted(){
        
        certifyImageView.hidden = true
        VIPimageView.hidden = true
        NameLable.textColor = UIColor.blackColor()
        //设置头像
        iconImageView.sd_setImageWithURL(status?.iconImageURL)
        //设置VIP等级
        VIPimageView.image = status?.ViplevelImage
        if VIPimageView.image != nil{
            VIPimageView.hidden = false
            NameLable.textColor = ThemeColor
        }
        //设置认证图标
        certifyImageView.image = status?.verifiedImage
        if certifyImageView.image != nil {
            certifyImageView.hidden = false
        }
        // 设置时间
        timeLable.text = status?.time
        // 设置来源
        fromLable.text = status?.comeFromStirng
        
        NameLable.text = status?.dataModel?.UserInfo?.name
        textLable.text = status?.dataModel?.text
        
        backView.imageCount =  setCollectinViewImageCount()
        backView.key =  setBackViewimageKey()
        pic_urlArray = setPic_urlArray()
        
        backView.picCollectionView.reloadData()
        
    }
    
    //MARK: - 懒加载子视图
    //头像
    lazy var iconImageView: UIImageView = {
        let icon = UIImageView(image: UIImage(named: "avatar_default"))
        icon.layer.cornerRadius = icon.frame.width * 0.5
        icon.layer.masksToBounds  = true
        icon.sizeToFit()
        return icon
    }()
    /// 名称
    lazy var NameLable : UILabel = {
        let lable = UILabel()
        lable.sizeToFit()
        return lable
    }()
    /// 认证图标
    lazy var certifyImageView: UIImageView = {
        let image = UIImageView()
        image.sizeToFit()
        return image
    }()
    /// VIP等级图标
    lazy var VIPimageView : UIImageView = {
        let image = UIImageView()
        image.sizeToFit()
        return image
    }()
    /// 发送时间
    lazy var timeLable : UILabel = {
        let time = UILabel()
        time.font = UIFont.systemFontOfSize(10)
        time.text = "刚刚"
        time.textColor = ThemeColor
        time.sizeToFit()
        return time
        
    }()
    /// 来源
    lazy var fromLable : UILabel = {
        let from = UILabel()
        from.font = UIFont.systemFontOfSize(10)
        from.textColor = UIColor.lightGrayColor()
        from.sizeToFit()
        return from
        
    }()
    /// 文本
    lazy var textLable : UILabel = {
        let text = UILabel()
        text.numberOfLines = 0
        //使用 preferredMaxLayoutWidth在自动布局时，会自动计算lable的高度
        //使用 breakMode 和 添加宽度约束 来换行时，会出现高度计算错了问题,从而导致整个cell的高度错误:妈蛋，之前被坑得好惨
        
        text.preferredMaxLayoutWidth = allMargin.screenWidth - 2 * allMargin.textMargin
        return text
    }()
    
    lazy var toolview : toolView = {
        let tool  = toolView()
        return tool
        
    }()
    
    lazy var backView:JkmbackView = {
        
        let  view = JkmbackView(dataSouce: self)
        
        return view
    }()

    //MARK:  - 设置约束
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        SetUI()
    }
    func SetUI(){
        
        contentView.addSubview(iconImageView)
        contentView.addSubview(NameLable)
        contentView.addSubview(certifyImageView)
        contentView.addSubview(VIPimageView)
        contentView.addSubview(timeLable)
        contentView.addSubview(textLable)
        contentView.addSubview(fromLable)
        contentView.addSubview(toolview)
        contentView.addSubview(backView)
        
        iconImageView.snp_makeConstraints { (make) in
            make.top.equalTo(contentView.snp_top).offset(10)
            make.left.equalTo(contentView.snp_left).offset(10)
            make.height.equalTo(iconImageView.frame.width)
            make.width.equalTo(iconImageView.frame.width)
        }
        
        NameLable.snp_makeConstraints { (make) in
            make.top.equalTo(iconImageView.snp_top)
            make.left.equalTo(iconImageView.snp_right).offset(20)
        }
        
        VIPimageView.snp_makeConstraints { (make) in
            make.left.equalTo(NameLable.snp_right).offset(5)
            make.centerY.equalTo(NameLable.snp_centerY)
        }
        
        certifyImageView.snp_makeConstraints { (make) in
            make.right.equalTo(iconImageView.snp_right)
            make.bottom.equalTo(iconImageView.snp_bottom)
        }
        timeLable.snp_makeConstraints { (make) in
            make.left.equalTo(iconImageView.snp_right).offset(20)
            make.bottom.equalTo(iconImageView.snp_bottom)
        }
        textLable.snp_makeConstraints { (make) in
            make.left.equalTo(iconImageView.snp_left)
            make.top.equalTo(iconImageView.snp_bottom).offset(20)
        }
        fromLable.snp_makeConstraints { (make) in
            make.right.equalTo(contentView.snp_right).offset(-20)
            make.centerY.equalTo(timeLable.snp_centerY)
        }
        backView.snp_makeConstraints { (make) in
            make.top.equalTo(textLable.snp_bottom).offset(20)
            make.left.equalTo(contentView.snp_left)
            make.right.equalTo(contentView.snp_right)
        }
        toolview.snp_makeConstraints { (make) in
            make.left.equalTo(contentView.snp_left)
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(backView.snp_bottom)
            make.height.equalTo(50)
        }
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// MARK: - UICollectionViewDataSource
extension BaseCell : UICollectionViewDataSource{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return backView.imageCount ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
        
        let url = pic_urlArray![indexPath.row]

        SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: url), options: SDWebImageOptions.init(rawValue: 0), progress: nil) { (image, _, _, _, _) in
            cell.contentView.layer.contents = image.CGImage
            cell.contentView.contentMode = .ScaleAspectFill
            cell.contentView.layer.masksToBounds = true
            
        }
        return cell
    }
    
}


//MARK: - 配图视图
class JkmbackView: UIView {
    
    var imageCount :Int?
    
    var key : String?
    
    lazy var forwardTextLable : UILabel = {
        let text = UILabel()
        text.numberOfLines = 0
        text.preferredMaxLayoutWidth = allMargin.screenWidth - 2 * allMargin.textMargin
        return text
        
    }()
    lazy var picCollectionView:UICollectionView = {
        let  flowLayout =  UICollectionViewFlowLayout()
        
        flowLayout.minimumInteritemSpacing = allMargin.picturesMargin
        flowLayout.minimumLineSpacing = allMargin.picturesMargin
        
        let images = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        
        images.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
        images.backgroundColor = UIColor.clearColor()
        return images
        
    }()
    init(dataSouce:UICollectionViewDataSource){
        super.init(frame:CGRectZero)
        setUI(dataSouce)
    }
    
    func setUI(dataSouce:UICollectionViewDataSource){
        
        addSubview(forwardTextLable)
        addSubview(picCollectionView)
        
        picCollectionView.dataSource = dataSouce
        
        forwardTextLable.snp_makeConstraints { (make) in
            make.left.equalTo(snp_left).offset(10)
            make.top.equalTo(snp_top).offset(20)
        }
        picCollectionView.snp_makeConstraints { (make) in
            make.left.equalTo(snp_left).offset(allMargin.picCollectionViewLeftMargin)
            make.top.equalTo(forwardTextLable.snp_bottom).offset(20)
            make.bottom.equalTo(snp_bottom).offset(-20)

        }
    }

    func orignalCell(){
        backgroundColor =  UIColor.clearColor()
        
        forwardTextLable.snp_updateConstraints { (make) in
            make.top.equalTo(snp_top)
        }
        picCollectionView.snp_updateConstraints{ (make) in
            make.top.equalTo(forwardTextLable.snp_bottom)
        }
        setCollectinSize()
        
    }

    func forwardCell(setText:(textlable : UILabel)->()){
        
        backgroundColor = UIColor(white: 0.94, alpha: 1)
        
        setCollectinSize()
        
        setText(textlable: forwardTextLable)
        
    }
    
    func setCollectinSize(){
        
        let (itemSize,collectin) = calculateCollectionViewSize()
        
        let flowLayout =  picCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        picCollectionView.snp_updateConstraints { (make) in
            make.size.equalTo(collectin)
        }
        
        if itemSize != CGSizeZero {
            flowLayout.itemSize = itemSize
        }
    
    }
    //MARK: 计算collectionViewCell的宽高和collectionView的宽高
    /**
     ### 计算collectionViewCell的size 和 collectionView的size
     
     - returns:  **cell的Size**  , **view的Size**
     */
    func calculateCollectionViewSize()->(CGSize,CGSize){
        let count = imageCount ?? 0
        //没有配图
        if  count ==  0 {
            
            return (CGSizeZero,CGSizeZero)
        }
        //1 张
        if count == 1{
            
            var imagesize = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key).size
            if imagesize.width > (allMargin.screenWidth - 20) {
                let scale = (allMargin.screenWidth - 20) / imagesize.width
                imagesize.width = imagesize.width * scale
                imagesize.height = imagesize.height * scale
            }
            return (imagesize,imagesize)
        }
        //4 张
        let margin = allMargin.picturesMargin
        
        if count == 4 {
            let col : CGFloat = 2
            let row : CGFloat = col
            let width :CGFloat = (allMargin.screenWidth - 2 * CGFloat( allMargin.picCollectionViewLeftMargin)  - (col - 1) * margin) / 2
            let height  = width
            return (CGSize(width: width,height:width) , CGSize(width:  (width + margin) * col - margin, height: (height + margin) * row - margin))
        }
        
        //其他
        let colum :CGFloat = count >= 3 ? 3 : 2
        let row:CGFloat = CGFloat( (count - 1) / 3  + 1)
        let width :CGFloat = (allMargin.screenWidth - 2 * CGFloat( allMargin.picCollectionViewLeftMargin)  - (colum - 1) * margin) / 3
        let height = width
        
        return(CGSize(width: width, height:height),CGSize(width:  (width + margin) * colum - margin, height: (height + margin) * row - margin))
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
//MARK: - cell底部工具条
class toolView : UIView{
    lazy  var relayButton: UIButton = {
        return UIButton(title: "转发", imageName: "timeline_icon_retweet", backgroundImageName: "timeline_card_middle_background")
        
    }()
    lazy  var commentButton: UIButton  = {
        return UIButton(title: "评论", imageName: "timeline_icon_comment", backgroundImageName: "timeline_card_middle_background")
        
    }()
    lazy var surpportButton : UIButton = {
        return UIButton(title: "赞", imageName: "timeline_icon_unlike", backgroundImageName: "timeline_card_middle_background")
    }()
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        addSubview(relayButton)
        addSubview(commentButton)
        addSubview(surpportButton)
        backgroundColor = UIColor(white: 0.93, alpha: 1)
        let width = UIScreen.mainScreen().bounds.width / 3
        let edge = -10
        relayButton.snp_makeConstraints { (make) in
            make.left.equalTo(snp_left)
            make.top.equalTo(snp_top)
            make.bottom.equalTo(snp_bottom).offset(edge)
            make.width.equalTo(width)
        }
        commentButton.snp_makeConstraints { (make) in
            make.left.equalTo(relayButton.snp_right)
            make.top.equalTo(snp_top)
            make.bottom.equalTo(snp_bottom).offset(edge)
            make.width.equalTo(width)
        }
        surpportButton.snp_makeConstraints { (make) in
            make.left.equalTo(commentButton.snp_right)
            make.top.equalTo(snp_top)
            make.bottom.equalTo(snp_bottom).offset(edge)
            make.width.equalTo(width)
        }
        
    }
}


//MARK: 子视图约束的间隔的结构体
private struct margins {
    let textMargin : CGFloat = 10
    let picCollectionViewLeftMargin = 10
    let picturesMargin : CGFloat = 5
    let screenWidth = UIScreen.mainScreen().bounds.width
    let screenHeight = UIScreen.mainScreen().bounds.height
}

private let allMargin = margins.init()
